package com.wxcms.ctrl;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.wxapi.process.MpAccount;
import com.wxapi.process.WxApiClient;
import com.wxapi.process.WxMemoryCacheClient;
import com.wxcms.domain.AccountOrg;
import com.wxcms.domain.Org;
import com.wxcms.service.OrgService;

/**
 * 
 */

@Controller
@RequestMapping("/wxcms/org")
public class OrgCtrl{

	@Autowired
	private OrgService entityService;

	@RequestMapping(value = "/getById")
	public ModelAndView getById(String id){
		entityService.getById(id);
		return new ModelAndView();
	}

	@RequestMapping(value = "/list")
	public  ModelAndView list(@ModelAttribute Org searchEntity){
		ModelAndView modelAndView = new ModelAndView("wxcms/orgList");
		List<Org> list = entityService.listForPage(searchEntity);
		modelAndView.addObject("pageList", list);
		modelAndView.addObject("cur_nav", "org");
		return modelAndView;
	}
	
	@RequestMapping(value = "/toMerge")
	public ModelAndView toMerge(Org entity){
		ModelAndView modelAndView = new ModelAndView("wxcms/orgMerge");
		Org org = new Org();
		if(entity.getId()!=null){
			org = entityService.getById(entity.getId().toString());
		}
		modelAndView.addObject("entity", org);
		return modelAndView;
	}

	@RequestMapping(value = "/doMerge")
	public ModelAndView doMerge(Org entity){
		if(entity.getId()!=null){
			entityService.update(entity);
		}
		else {
			entityService.add(entity);
		}
		return new ModelAndView("redirect:/wxcms/org/list.html");
	}

	@RequestMapping(value = "/delete")
	public ModelAndView delete(Org entity){
		ModelAndView modelAndView = new ModelAndView("redirect:/wxcms/org/list.html");
		entityService.delete(entity);
		return modelAndView;
	}
	
	@RequestMapping(value = "/viewQrcode")
	public ModelAndView viewQrcode(Org entity){
		ModelAndView modelAndView = new ModelAndView("wxcms/viewqrcode");
		String ticket = entity.getTicket();
		modelAndView.addObject("ticket",ticket);
		return modelAndView;
	}
	
	@RequestMapping(value = "/createQrcode")
	public ModelAndView createQrcode(Org entity){
		ModelAndView modelAndView = new ModelAndView("wxcms/viewqrcode");
		MpAccount mpAccount = WxMemoryCacheClient.getSingleMpAccount();
		String ticket = WxApiClient.createQRCodeLimitTicket(entity.getOrgId(), mpAccount);
		if(ticket==null){
			return modelAndView;
		}
		Org org = entityService.getById(entity.getId().toString());
		if(org.getId()!=null){
			org.setTicket(ticket);
			entityService.update(org);
		}
		modelAndView.addObject("ticket",ticket);
		return modelAndView;
	}

}
